<template>
  <div class="training-report">
    <!-- 顶部信息栏 -->
    <div class="top-info">
      <span class="label">培训班名称</span> <span class="value">{{ trainingClassName }}</span>
      <span class="label">班主任</span> <span class="value">{{ headTeacherName }}</span>
      <span class="label">培训时间</span> <span class="value">{{ trainingClassTime }}</span>
    </div>

    <!-- 搜索区域（支持显示/隐藏） -->
    <div class="search-area" v-if="showSearch">
      <el-form inline :model="searchForm" class="search-form" label-width="70px">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.studentName" placeholder="请输入姓名" style="width:150px"></el-input>
        </el-form-item>
        <el-form-item label="手机号码">
          <el-input v-model="searchForm.phonenumber" placeholder="请输入手机号码" style="width:150px"></el-input>
        </el-form-item>
        <el-form-item label="证件编号">
          <el-input v-model="searchForm.idNumber" placeholder="请输入证件编号"  style="width:150px"></el-input>
        </el-form-item>
        <el-form-item label="填报状态">
          <el-select v-model="searchForm.satisfactionSurveyStatus" placeholder="选择填报状态"  style="width:150px">
            <el-option label="全部" value=""></el-option>
            <el-option label="已填报" value="1"></el-option>
            <el-option label="未填报" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="50px">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 功能按钮栏 -->
    <div class="action-buttons">
      <!-- <el-button type="default" @click="handleExport">
        <i class="el-icon-download"></i> 导出
      </el-button>
      <el-button type="default" @click="handleShowQrCode">
        <i class="el-icon-qrcode"></i> 班级二维码
      </el-button> -->
      <el-button type="default" style="margin-left: 20px;" @click="handleToggleSearch">
        <i :class="showSearch ? 'el-icon-up' : 'el-icon-down'"></i>
        {{ showSearch ? '隐藏搜索' : '显示搜索' }}
      </el-button>
      <el-button type="default" @click="handleRefresh">
        <i class="el-icon-refresh"></i> 刷新
      </el-button>
    </div>

    <!-- 数据表格（已适配接口字段） -->
    <el-table :data="tableData" border style="width: 100%;" v-loading="tableLoading">
      <el-table-column type="selection" width="55"></el-table-column>
      <!-- 编号：对应satisfactionSurveyId -->
      <!-- <el-table-column prop="satisfactionSurveyId" label="编号" width="80"></el-table-column> -->
      <!-- 姓名：对应studentName -->
      <el-table-column prop="studentName" label="姓名" width="100"></el-table-column>
      <!-- 证件编号：对应idNumber -->
      <el-table-column prop="idNumber" label="证件编号" width="200"></el-table-column>
      <!-- 电话：对应phonenumber -->
      <el-table-column prop="phonenumber" label="电话" width="120"></el-table-column>
      <!-- 培训安排评分：对应trainingScheduleScore -->
      <el-table-column prop="trainingScheduleScore" label="培训安排" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.trainingScheduleScore || '-' }}</span>
        </template>
      </el-table-column>
      <!-- 服务质量评分：对应serviceQualityScore -->
      <el-table-column prop="serviceQualityScore" label="服务质量" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.serviceQualityScore || '-' }}</span>
        </template>
      </el-table-column>
      <!-- 课程安排评分：对应courseScheduleScore -->
      <el-table-column prop="courseScheduleScore" label="课程安排" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.courseScheduleScore || '-' }}</span>
        </template>
      </el-table-column>
      <!-- 教师授课质量评分：对应teachingQualityScore -->
      <el-table-column prop="teachingQualityScore" label="教师授课质量" width="120" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.teachingQualityScore || '-' }}</span>
        </template>
      </el-table-column>
      <!-- 培训效果评分：对应trainingEffectivenessScore -->
      <el-table-column prop="trainingEffectivenessScore" label="培训效果" width="100" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.trainingEffectivenessScore || '-' }}</span>
        </template>
      </el-table-column>
      <!-- 意见建议：对应commentsSuggestions -->
      <el-table-column prop="commentsSuggestions" label="意见建议" width="120" show-overflow-tooltip></el-table-column>
      <!-- 改进措施：对应improvementMeasures -->
      <el-table-column prop="improvementMeasures" label="改进措施" width="120" show-overflow-tooltip></el-table-column>
      <!-- 最大收获：对应harvest -->
      <el-table-column prop="harvest" label="最大收获" width="120" show-overflow-tooltip></el-table-column>
      <!-- 期望培训：对应expectationTraining -->
      <el-table-column prop="expectationTraining" label="期望培训" width="120" show-overflow-tooltip></el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination">
      <span class="total">共 {{ total }} 条</span>
      <el-select v-model="pageSize" @change="handlePageSizeChange" size="mini">
        <el-option label="10条/页" value="10"></el-option>
        <el-option label="20条/页" value="20"></el-option>
        <el-option label="50条/页" value="50"></el-option>
      </el-select>
      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, jumper"
        size="small"
      ></el-pagination>
    </div>

    <!-- 班级二维码对话框 -->
    <el-dialog
      title="班级二维码"
      :visible.sync="qrCodeDialogVisible"
      width="300px"
      :close-on-click-modal="false"
    >
      <div style="text-align: center; padding: 20px;">
        <el-image
          :src="qrCodeUrl"
          alt="班级二维码"
          style="width: 200px; height: 200px;"
          :preview-src-list="[qrCodeUrl]"
        >
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        <p style="margin-top: 10px; color: #666;">扫码查看班级详情</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTrainingClass,
  trainingClassList,
  getClassQrCode // 补充导入二维码接口
} from "@/api/training/TrainingClass";
import {
  listBySatisfactionSurveyDto,
  exportTrainingReport // 补充导入导出接口
} from "@/api/training/satisfactionSurvey";

export default {
  name: 'TrainingReport',
  props: {
    classId: {
      type: String,
      required: true,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      trainingClassName: "",
      headTeacherName: "",
      trainingClassTime: "",

      // 搜索表单数据（已与接口参数对应）
      searchForm: {
        studentName: '',
        phonenumber: '',
        idNumber: '',
        satisfactionSurveyStatus: '' // 默认为空（全部）
      },

      // 表格数据
      tableData: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
      tableLoading: false,

      // 按钮相关状态
      showSearch: true,
      qrCodeDialogVisible: false,
      qrCodeUrl: ""
    }
  },
  watch: {
    classId: {
      immediate: true,
      handler(newVal) {
        if (newVal && this.visible) {
          this.getClassInfo();
          this.fetchTableData();
        }
      }
    },
    visible(newVal) {
      if (newVal && this.classId) {
        this.getClassInfo();
        this.fetchTableData();
      }
    }
  },
  methods: {
    // 获取班级基本信息
    async getClassInfo() {
      if (!this.classId) return;

      try {
        const res = await getTrainingClass(this.classId);
        if (res.code === 200) {
          const classRes = await trainingClassList({
            trainingClassCode: res.data.trainingClassCode
          });

          this.trainingClassName = res.data.trainingClassName || '未知班级';
          this.headTeacherName = classRes.rows[0]?.headTeacher1Name || classRes.rows[0]?.headTeacher2Name || '未知';
          this.trainingClassTime = `${res.data.startDate || ''} 至 ${res.data.endDate || ''}`;
        } else {
          this.$message.error(res.msg || '获取班级信息失败');
        }
      } catch (err) {
        this.$message.error('获取班级信息失败：' + (err.response?.data?.msg || err.message));
      }
    },

    // 获取报表数据（已适配接口返回格式）
    async fetchTableData() {
      if (!this.classId) return;

      this.tableLoading = true;
      try {
        const params = {
          trainingClassId: this.classId,
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          ...this.searchForm
        };

        const res = await listBySatisfactionSurveyDto(params);
        if (res.code === 200) {
          this.tableData = res.rows || [];
          this.total = res.total || 0;
        } else {
          this.$message.error(res.msg || '获取报表数据失败');
          this.tableData = [];
          this.total = 0;
        }
      } catch (err) {
        console.error('获取报表数据失败:', err);
        this.$message.error('网络异常，获取数据失败');
        this.tableData = [];
        this.total = 0;
      } finally {
        this.tableLoading = false;
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchTableData();
    },

    // 重置搜索
    handleReset() {
      this.searchForm = {
        studentName: '',
        phonenumber: '',
        idNumber: '',
        satisfactionSurveyStatus: ''
      };
      this.currentPage = 1;
      this.fetchTableData();
    },

    // 导出数据
    async handleExport() {
      if (!this.classId) {
        this.$message.warning('班级信息异常，无法导出');
        return;
      }

      try {
        this.$message.success('开始导出数据...');
        const params = {
          classId: this.classId,
          ...this.searchForm
        };

        const res = await exportTrainingReport(params);
        // 处理文件流
        const blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `${this.trainingClassName || '培训报表'}.xlsx`;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
        document.body.removeChild(a);
        this.$message.success('导出成功');
      } catch (err) {
        this.$message.error('导出失败：' + (err.response?.data?.msg || err.message));
      }
    },

    // 显示班级二维码
    async handleShowQrCode() {
      if (!this.classId) {
        this.$message.warning('班级信息异常，无法获取二维码');
        return;
      }

      try {
        const res = await getClassQrCode(this.classId);
        if (res.code === 200) {
          this.qrCodeUrl = res.data.qrCodeUrl;
          this.qrCodeDialogVisible = true;
        } else {
          this.$message.error(res.msg || '获取二维码失败');
        }
      } catch (err) {
        this.$message.error('获取二维码失败：' + (err.response?.data?.msg || err.message));
      }
    },

    // 切换搜索区域
    handleToggleSearch() {
      this.showSearch = !this.showSearch;
    },

    // 刷新数据
    handleRefresh() {
      this.fetchTableData();
      this.$message.success('已刷新');
    },

    // 分页大小变更
    handlePageSizeChange(val) {
      this.pageSize = val;
      this.fetchTableData();
    },

    // 当前页变更
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchTableData();
    },

    // 关闭弹窗（通知父组件）
    closeDialog() {
      this.$emit('update:visible', false);
    }
  }
}
</script>

<style scoped>
.training-report {
  padding: 15px;
  max-height: calc(100vh - 120px);
  overflow-y: auto;
  box-sizing: border-box;
}
.top-info {
  margin-bottom: 15px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 25px;
  align-items: center;
}
.label {
  font-weight: 600;
  margin-right: 5px;
  color: #606266;
}
.value {
  color: #303133;
  word-break: break-all;
}
.search-area {
  margin-bottom: 15px;
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background: #fff;
}
.search-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}
.action-buttons {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}
.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-top: 15px;
  padding: 10px 0;
  flex-wrap: wrap;
  gap: 10px;
}
.total {
  margin-right: 5px;
  color: #606266;
  font-size: 14px;
}
.image-slot {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  color: #909399;
}

/* 表格溢出处理 */
::v-deep .el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .top-info {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .search-form {
    flex-direction: column;
    align-items: flex-start;
  }

  .pagination {
    justify-content: center;
  }
}
</style>
